import 'dart:typed_data';

import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class QiniuUploader extends StatefulWidget {
  @override
  _QiniuUploaderState createState() => _QiniuUploaderState();
}

class _QiniuUploaderState extends State<QiniuUploader> {
  var token =
      '-E9_H7xGiKSWzvCHkIYeHaxDPgWkhNhlqYKVRJco:IM6d4ePzlJhDbmTJBCqAmJT6tJU=:eyJzYXZlS2V5IjoiJHt5ZWFyfSR7bW9ufSR7ZGF5fS8kKGV0YWcpJChleHQpIiwic2NvcGUiOiJib2JvLWRlbW8iLCJkZWFkbGluZSI6MTU4NzIxOTkzNH0=';
  Dio dio;
  Uint8List bytes;

  @override
  void initState() {
    super.initState();
    dio = Dio();
    dio.interceptors.add(LogInterceptor(responseBody: true));
    _loadImage();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text('七牛上传'),
      ),
      body: Container(
        child: Center(
          child:
              bytes != null ? Image.memory(bytes) : CircularProgressIndicator(),
        ),
      ),
    );
  }

  _loadImage() async {
    var data = await rootBundle.load('assets/gakki.jpg');
    bytes = data.buffer.asUint8List();
    var form = FormData.fromMap({
      'token': token,
      'file': MultipartFile.fromBytes(bytes.cast<int>()),
    });
    dio.post(
      'http://up.qiniup.com',
      data: form,
      onSendProgress: (send, total) {
        print('$send / $total');
      },
    );
    setState(() {});
  }
}
